#! /usr/bin/env bash

# Exit on error
# Error on undefined variable
set -e
set -u

TMPDIR="${TMPDIR-/tmp}"

# Usage
if [ "${#}" -ne "1" ]
then
	echo "usage: ${0} <version>"
	echo "Update all references to the version number"
	exit 1
fi

# Determine source path
SOURCE_PATH="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"

# Get version number
VERSION="${1}"
VERSION_SHORT="$(echo "${VERSION}" | cut -d'.' -f'1,2')"

# some system may not have -i option
sedInPlace () {
	TMP_FILE="$(mktemp ${TMPDIR}/config.XXXXXXXXXX)"
	sed "${1}" "${2}" > "${TMP_FILE}"
	mv "${TMP_FILE}" "${2}"
}

# Update Defs.h
sedInPlace 's|\(#define \+PRODUCT_VERSION *"\)[^"]*"|\1'"${VERSION}"'"|' "${SOURCE_PATH}/daemon/src/common/Defs.h"

# Update download-dpk
sedInPlace 's|version=.*|version='"${VERSION}"'|' "${SOURCE_PATH}/download-paks"
chmod +x "${SOURCE_PATH}/download-paks"

# Update Info.plist
sedInPlace '/<key>CFBundleVersion<\/key>/{N;s|<string>[^<]*</string>|<string>'"${VERSION}"'</string>|}' "${SOURCE_PATH}/macosx/Info.plist"

# Update menu_main.rml
sedInPlace '/blocklink.*Alpha/s/Alpha \([0-9\.]\+\)/Alpha '"${VERSION_SHORT}"'/' "${SOURCE_PATH}/pkg/unvanquished_src.dpkdir/ui/menu_main.rml"

# Update m# Update menu_main.rml
sedInPlace '/blocklink.*Alpha/s/Alpha \([0-9\.]\+\)/Alpha '"${VERSION_SHORT}"'/' "${SOURCE_PATH}/pkg/unvanquished_src.dpkdir/ui/menu_ingame.rml"
